<template>
  <UserOrLogin/>
  <n-grid :cols="11" :x-gap="12" :y-gap="gridSpace">
    <n-gi :span="3" :offset="showAddOrEditCard?0:4">
      <TaskDataTable
          title="今日事今日毕"
          :data="todayTask"
          :columns="todayTaskColumns"
          :table-max-height="tableMaxHeight"
          :style="'width: 500px'"
          @onModify="onModify"
          @onClickPublic="onUpdatePublicStatus"
          @onClickDone="onUpdateStatus"/>
    </n-gi>
    <n-gi v-if="!showAddOrEditCard" :span="1" :offset="3">
      <n-button type="primary" @click="showAddOrEditCard=true">
        <template #icon>
          <n-icon>
            <Pencil/>
          </n-icon>
        </template>
        又有活啦
      </n-button>
    </n-gi>
    <n-gi v-if="showAddOrEditCard" :span="8">
      <AddTask @onCommit="closeAddCard" :edit-data="modifyData"/>
    </n-gi>
    <n-gi :span="11">
      <TaskDataTable
          title="让我瞅瞅哪天的事儿还没办完"
          :editable="true"
          :data="allTask"
          :columns="allTaskColumns"
          :table-max-height="tableMaxHeight"
          :pagination="true"
          :page-count="pageCount"
          @onPageInfoChange="onPageInfoChange"
          @onUpdatePublicStatus="onUpdatePublicStatus"
          @onUpdateStatus="onUpdateStatus"
          @onModify="onModify"
          @onClickPublic="onUpdatePublicStatus"
          @onClickDone="onUpdateStatus"
      />
    </n-gi>
  </n-grid>
</template>

<script setup>

import TaskDataTable from "../components/task/TaskDataTable.vue";
import {h, inject, onMounted, ref} from "vue";
import {NTag} from "naive-ui";
import {getSelfTask, getTaskDetail, updatePublic, updateStatus} from "../api/taskApi.js";
import UserOrLogin from "../components/common/UserOrLogin.vue";
import AddTask from "../components/task/AddTask.vue";
import {CloudUpload, Pencil} from "@vicons/tabler";

onMounted(() => {
  updateBothTodayAndAll()
})

const getStatusTagType = inject('getStatusTagType')

const todayTaskColumns = ref([
  {
    title: '状态',
    key: 'statusName',
    align: 'center',
    titleAlign: 'center',
    width: 80,
    render(row) {
      return h(
          NTag, {
            type: getStatusTagType(row.status.code)
          },
          {default: () => row.status.name}
      )
    }
  },
  {
    title: '待办',
    key: 'task',
    align: 'center',
    titleAlign: 'center',
    render(row) {
      return h(
          'p', {
            style: {
              textDecoration: row.status.code === 2 ? 'line-through' : ''
            }
          },
          {
            default: () => row.title
          }
      )
    }
  }
])
const todayTask = ref([])

const allTaskColumns = ref([
  {
    title: '状态',
    key: 'statusName',
    align: 'center',
    titleAlign: 'center',
    width: 80,
    render(row) {
      return h(
          NTag, {
            type: getStatusTagType(row.status.code)
          },
          {default: () => row.status.name}
      )
    }
  },
  {
    title: '时间',
    key: 'createAt',
    align: 'center',
    titleAlign: 'center',
    width: 120
  },
  {
    title: '待办',
    key: 'title',
    align: 'center',
    titleAlign: 'center',
    width: window.innerWidth * 0.1,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '详情',
    key: 'content',
    align: 'center',
    titleAlign: 'center',
    ellipsis: {
      tooltip: true
    }
  }
])
const allTask = ref([])

const tableMaxHeight = ref(window.innerHeight * 0.25)
const gridSpace = ref(window.innerHeight * 0.05)

const searchTaskObj = ref({
  page: 1,
  limit: 10,
  text: null,
  status: null,
  createAt: null,
  needContent: true
})
const pageCount = ref(0)

const showAddOrEditCard = ref(false)

const modifyData = ref(null)

function loadTodayTask() {
  return new Promise((resolve, reject) => {
    getSelfTask({
      page: -1,
      limit: -1,
      createAt: new Date().getTime(),
    }).then(resp => {
      todayTask.value = resp.data.item ? resp.data.item : []
      resolve('success')
    }).catch(err => {
      console.log(err)
      reject('error')
    })
  })
}

function searchAllTask() {
  return new Promise((resolve, reject) => {
    getSelfTask(searchTaskObj.value).then(resp => {
      allTask.value = resp.data.item ? resp.data.item : []
      pageCount.value = Math.ceil(resp.data.total / searchTaskObj.value.limit)
      resolve('success')
    }).catch(err => {
      console.log(err)
      reject('error')
    })
  })
}

function onPageInfoChange(pageInfo) {
  searchTaskObj.value.page = pageInfo.currentPage
  searchTaskObj.value.limit = pageInfo.pageSize
  searchAllTask()
}

function onUpdateStatus(taskIds, status) {
  updateStatus(taskIds, status).then(resp => {
    updateBothTodayAndAll()
  }).catch(err => console.log(err))
}

function onUpdatePublicStatus(taskIds, isPublic) {
  updatePublic(taskIds, isPublic).then(resp => {
    updateBothTodayAndAll()
  }).catch(err => console.log(err))
}

function updateBothTodayAndAll() {
  loadTodayTask().then(() => {
    searchAllTask().then(() => {
      updateModifyData()
    })
  })
}

function updateModifyData() {
  if (!modifyData.value) {
    return
  }
  for (const t of todayTask.value) {
    if (modifyData.value.id === t.id) {
      modifyData.value = JSON.parse(JSON.stringify(t))
      return
    }
  }
  for (const t of allTask.value) {
    if (modifyData.value.id === t.id) {
      modifyData.value = JSON.parse(JSON.stringify(t))
      return
    }
  }
}

function closeAddCard(success) {
  showAddOrEditCard.value = false
  modifyData.value = null
  if (success) {
    updateBothTodayAndAll()
  }
}

function onModify(data) {
  console.log(13123)
  getTaskDetail(data.id).then(resp => {
    modifyData.value = resp.data
    showAddOrEditCard.value = true
  }).catch(err => console.log(err))
}

</script>

<style scoped>
</style>